package com.nut.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nut.course.common.Result;
import com.nut.course.entity.Demo;
import com.nut.course.mapper.BizDemoMapper;
import com.nut.course.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Set;

@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    private BizDemoMapper bizDemoMapper;

    @Override
    public Result<IPage<Demo>> list(String name, Integer status, Integer pageNo, Integer pageSize) {
        Page<Demo> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNo);

        LambdaQueryWrapper<Demo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(name)) {
            queryWrapper.like(Demo::getName, name);
        }
        if (status != null) {
            queryWrapper.eq(Demo::getStatus, status);
        }
        queryWrapper.orderByDesc(Demo::getId);

        IPage<Demo> list = bizDemoMapper.selectPage(page, queryWrapper);

        return Result.ok(list);
    }

    @Override
    public Demo getById(Serializable id) {
        return bizDemoMapper.selectById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result add(Demo demo) {
        bizDemoMapper.insert(demo);
        int i = 1/0;
        return Result.ok();
    }

    @Override
    public Result updateById(Demo demo) {
        bizDemoMapper.updateById(demo);
        return Result.ok();
    }

    @Override
    public Result deleteByIds(Set<Integer> ids) {
        for (Integer id : ids) {
            bizDemoMapper.deleteById(id);
        }
        return Result.ok();
    }

}
